/*------------------------------------------------------------------------------
 * @file    TIM_SCHEDULER.C
 * @author  嵌入式王子
 * @email   donminedm@163.com
 * @date    2024/07/31 21:44:00
 * @brief   开源的嵌入式软件包，本人不对此代码负责任
 * -----------------------------------------------------------------------------*/
#include "tim_scheduler.h"
#include "log.h"

static task_blk *__tasks = NULL;

void task_enable(task_list t, uint8_t enable)
{
    if (__tasks == NULL)
        return;
    __tasks[t].state = enable ? TASK_NOT_RUN : TASK_SUSPEND;
}

void task_tick()
{
    task_list t = 0;
    if (__tasks == NULL)
        return;
    // 遍历整个任务数组，更新任务的计时
    for (t = 0; t < TASK_MAX; t++)
    {
        if (__tasks[t].state == TASK_NOT_RUN) // 判断任务是否被挂起
        {
            if (__tasks[t].tick++ == __tasks[t].intel) // 是否达到任务间隔
            {
                logd("task[%d] to ready", t);
                __tasks[t].state = TASK_READY; // 任务进入就绪状态
                __tasks[t].tick = 0;           // 计时器重载
            }
        }
    }
}

void task_scheduler()
{
    task_list t = 0;
    uint32_t tick = 0;
    if (__tasks == NULL)
        return;
    for (t = 0; t < TASK_MAX; t++) // 遍历整个任务数组，运行待启动的任务
    {
        if (__tasks[t].state == TASK_READY) // 只有任务进入就绪状态才能运行
        {
            logd("task[%d] to run", t);
            __tasks[t].state = TASK_RUN; // 更改成运行状态
            // 开始计时
            tick = TASK_GET_TICK();
            if (__tasks[t].task_fnc != NULL) // 任务函数指针是否存在
                __tasks[t].task_fnc();       // 任务启动
            // 结束计时
            __tasks[t].use_time = TASK_GET_TICK() - tick;
            if (__tasks[t].state != TASK_SUSPEND) // 防止任务运行时被挂起
            {
                __tasks[t].state = TASK_NOT_RUN; // 更改成未运行状态
            }
            if (__tasks[t].use_time > __tasks[t].intel)
            {
                logw("task[%d] use time overflow");
            }
            else
                logd("task[%d] use time %d ms", t, __tasks[t].use_time);
        }
    }
}

void task_init(task_blk _task[])
{
    __tasks = _task;
    if (__tasks == NULL)
        logw("__tasks == NULL");
	logi("load success");
}

void task_printf()
{
    task_list t = 0;
    uint32_t tick = 0;
    if (__tasks == NULL)
        return;
    logi("| no | state | intel | tick | usetime |");
    for (t = 0; t < TASK_MAX; t++) // 遍历整个任务数组，运行待启动的任务
    {
        logi("| %02d | %d |%08d | %08d | %08d |", t, __tasks[t].state, __tasks[t].intel, __tasks[t].tick, __tasks[t].use_time);
    }
}